<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 商户管理
 *
 * @icon fa fa-circle-o
 */
class Merchant extends Backend
{

    /**
     * Merchant模型对象
     * @var \app\admin\model\Merchant
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;
        // $this->view->assign("isStatusList", $this->model->getIsStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        $offset = $this->request->param("offset");
        $limit = $this->request->param("limit");
        $defaultWhere = ["is_typs" => 1];
        $lists = [];
        $total = Db::name("user")->where($defaultWhere)->count();
        if ($total) {
            $lists = Db::name("user")
                ->alias("a")
                ->join("(select id ids,user_id,concat(province,city,district,address) addr,from_unixtime(active_time , '%Y-%m-%d %H:%i:%s') active_time from fd_machine_address ) b", "a.id=b.user_id", 'left')
                ->join("(select id ids,sale_id,real_name,INSERT ( real_idcard, 4, 11, '***********' ) real_idcard,card_front,card_back,license from fd_user_card ) c", "a.id=c.sale_id", 'left')
                ->join("(select uid,case status when 1 then '正常' when 2 then '已注销' when 3 then '已关闭' end  snick  from fd_merchant_status ) s" , "a.id=s.uid" , "left")
                ->where($defaultWhere)->limit((int)$offset, (int) $limit)->select();
            if ($lists) {
                foreach ($lists as $key => $value) {
                    $lists[$key]['volume'] = $this->todayVisit($value["mercode"]);
                    $lists[$key]['todayNums'] = $this->todayRegister($value["id"]);
                    $lists[$key]['nums'] = $this->model->where("mer_id", $value["id"])->count();
                    $lists[$key]['avatar'] = $value['avatar'] ? cdnurl($value['avatar'], true) : letter_avatar($value['nickname']);
                    $lists[$key]['card_front'] = $value['card_front'] ? cdnurl($value['card_front'], true) : letter_avatar('无');
                    $lists[$key]['card_back'] = $value['card_back'] ? cdnurl($value['card_back'], true) : letter_avatar('无');
                    $lists[$key]['license'] = $value['license'] ? cdnurl($value['license'], true) : letter_avatar('无');
                }
            }
        }
        $result = ['total' => $total, 'rows' => $lists];
        return json($result);
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = Db::name("user")
            ->alias('a')
            ->join("( select uid,status,from_unixtime(reg_time,'%Y-%m-%d') regtime from  fd_merchant_status ) b", "a.id = b.uid", 'left')
            ->where("id", $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $check = Db::name("merchant_status")->where("uid", $ids)->count();
            if ($check) {
                // 注销 - 解绑名下机具（广告机）
                $data["status"] = $params["status"];
                $data["out_time"] = strtotime(date("Y-m-d", time()));
                $ret = Db::name("merchant_status")->where("uid", $ids)->update($data);
                if ($ret) {
                    $update["is_bind"] = 2;
                    $result = Db::name("machine")->where("number", $params["mercode"])->update($update);
                    if ($result) {
                        Db::commit();
                    }
                }
            }
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 今日注册
     */
    public function todayRegister($id)
    {
        return $this->model->where("mer_id", $id)->where("from_unixtime(jointime, '%Y%m%d') = '" . date("Ymd", time()) . "'")->count();
    }

    /**
     * 今日访问
     */
    public function todayVisit($code)
    {
        return  Db::name("logs_access")->where("codes", $code)->where("times", strtotime(date("Y-m-d", time())))->count();
    }
}
